<template>
	<view v-if="showPopup">
		<zan-popup :show="showModal&&getType!=2">
			<view class="popup">
				<view class="top">
					<view class="title">温馨提示</view>
					<view class="content">需要您同意获取{{getType==0?'用户信息进行登录操作':'手机号码进行账号绑定'}}</view>
				</view>
				<view class="btn_bottom">
					<view class="return_icon" @tap.stop="failCallBack">等等再说</view>
					<view class="next_icon">
						{{getType==0?'获取信息':'授权登录'}}
						<button v-if="getType==0" class="share-btn" open-type="getUserInfo" @getuserinfo="getUserInfo"></button>
						<button v-else-if="getType==1" class="share-btn" open-type="getPhoneNumber" @getphonenumber="getWxPhone"></button>
					</view>
				</view>
			</view>
		</zan-popup>
	</view>
</template>

<script>
	import zanPopup from '@/components/popup/index.vue'; //弹出层
	import { commonMixinFun } from '@/static/mixins/common.js'; // 公共
	import request from '@/static/uitls/request.js';
	const app = getApp();
	import API from '@/static/api/index.js';
	export default{
		mixins: [commonMixinFun],
		components: {
			zanPopup
		},
		props: {
			showPopup: {
				type:[Boolean,String],
				default: false
			},
			getInfoType:{ // 获取信息类型  0 获取用户信息  1 获取手机号  2可以直接进行登录   其它值时当前页面自行判断
				type:[Number,String],
				request:false,
				default: 0
			},
			identity:{ // 用户身份， 0 学生 1 教师
				type:[Number,String],
				request:false,
				default: 0
			}
		},
		data(){
			return {
				comIdentity:0,
				showModal:false,
				isShowSelectTeacherModel:false,// 是否已经显示了选择教师登录模态框
				wxapp_openid:'',
				getType:0,
				avatar: '',
				nickname: '',
				iv:'',
				encryptedData:''
			}
		},
		created() {
			this.comIdentity = this.identity // 解决直接修改props传参
		},
		watch:{
			showPopup(val,oldVal){
				this.getType=this.getInfoType
				let _this = this;
				app._log('显示类型',this.getType)
				app._log('显示状态',val)
				if(val){
					this.getSetting(res=>{
						_this.setGetSetting(res,true)
					});
				}
			},
			getType(val,oldVal){
				app._log(val)
				if(val==2){
					this.showLoading('正在登录中...')
					this.loginFun((code,data) => {
						app._log(code,data)
						if (code == 1) {
							this.updateUserInfo()
						} else if(code==992){ // 需要去登录教师端
							this.toLoginTeacher();
							this.hideLoading();
						}else if (code == 9997) {// 只有未登录的才处理
							this.wxapp_openid = data.wxapp_openid;
							this.toDecrypt()
						}else{
							this.failCallBack();
						}
					},err=>{
						this.hideLoading()
						this.showToast(err.msg || '登录失败');
					});
				}
			}
		},
		methods:{
			// 获取用户信息  1
			getUserInfo(e) {
				let _this = this;
				let { userInfo } = e.detail;
				if (userInfo) {
					// 用户同意获取
					_this.avatar = userInfo.avatarUrl;
					_this.nickname = userInfo.nickName;
					_this.getType=1;  //修改当前状态 改成获取手机号码
				} else {
					_this.closeCoursePopup();
				}
			},
			
			// 获取手机号 2
			getWxPhone(e) {
				let { encryptedData, iv } = e.detail;
				if (encryptedData && iv) { // 获取手机号码成功
					app._log(encryptedData, iv);
					this.iv =iv;
					this.encryptedData =encryptedData;
					this.getType=2; // 修改当前状态 改成登录
				} else {
					this.showToast('获取手机号失败');
				}
			},
			
			
			
			successCallBack(){ // 成功回调事件
				this.$emit('confirm');
				uni.$emit('loginSuccessCallBack');
			},
			failCallBack(){ // 失败回调事件
				console.log('关闭')
				// this.$emit('closeLoginPopup');
				this.$emit('close');
				
			},
			//获取设置项
			getSetting(callback){
				uni.getSetting({
				   success:({authSetting})=>{ //用户已同意授权用户信息
					app._log(authSetting);
					callback(authSetting)
				   }
				})
			},
			// 设置获取的参数
			setGetSetting(res,state=false){
				let _this = this;
				if(res['scope.userInfo']){
					uni.getUserInfo({
						provider: 'weixin',
						success:({errMsg,userInfo,iv,encryptedData})=>{
							if(errMsg=="getUserInfo:ok"){
								app._log(userInfo,iv,encryptedData);
								userInfo.avatarUrl?_this.avatar = userInfo.avatarUrl:'';
								userInfo.nickName?_this.nickname = userInfo.nickName:'';
								_this.getType=1;
							}
						},
						complete: () => {
							this.showModal=state
						}
					});
				}else{
					this.showModal=state
				}
				setTimeout(()=>{
					app._log('_this.getType',_this.getType)
				},1000)
			},
			closeCoursePopup(delay = 0) {
				this.failCallBack();
			},
			// 需要去登录学生端
			toLoginStudent(){
				let _this = this;
				this.loginFun((code,data) => {
					if (code == 1) {
						app._log('登录了')
						this.successCallBack();
					} else if(code==992){ // 需要去登录教师端
						this.toLoginTeacher()
					}else if (code == 9997) { // 只有未登录的才处理
						this.wxapp_openid = data.wxapp_openid;
						this.toDecrypt()
					}else{
						this.failCallBack();
					}
					this.hideLoading();
				});
			},
			toDecrypt(){
				API.decrypt({
					wxapp_openid: this.wxapp_openid,
					encryptedData: this.encryptedData,
					iv: this.iv
				}).then(({ code, data, msg }) => {
					app._log(data)
					if (code == 1) {
						this._bind(data.phoneNumber)
						// this.updateUserInfo()
					} else {
						this.failCallBack();
						this.showToast(msg || '获取手机号失败');
					}
				}).catch(err => {
					this.failCallBack();
					this.showToast(err.msg || '获取手机号失败');
				});
			},
			// 需要去登录教师端
			toLoginTeacher(){
				if(!this.isShowSelectTeacherModel){
					this.isShowSelectTeacherModel=true
					uni.showModal({
						title:'您是教师',
						content:'是否回到教师端？',
						success: (res) => {
							if(res.confirm){
								this.comIdentity=1;
								this.loginFun((code,data)=>{
									app._log('身份',code);
									this.successCallBack();
									let arr = ['pages/teacher_detail/index'];
									let pages = getCurrentPages();
									if(arr.findIndex(o=>o==pages[pages.length-1].route)!=-1){
										this.pageTo('/pages/index/index')
									}
								})
							}
						},
						complete: () => {
							this.closeCoursePopup()
							this.isShowSelectTeacherModel=false
						}
					})
				}
			},
			_bind(phoneNumber){
				let _this=this;
				let {comIdentity}=this
				API.bind({wxapp_openid:this.wxapp_openid,mobile:phoneNumber}).then(res=>{
					if (res.code == 1) {
						// 登录请求
						uni.login({
						  success: function (res) {
						    request({
						      url: `/${comIdentity==0?'api':'teacher'}/v1/user/auth?code=${res.code}`, 
						    }).then(res => {
								app._log(res)
								if(res.code == 1) {
									  uni.setStorageSync('app_token',res.data.token);
										app.globalData.LOGION = true;
										if(comIdentity==0){ //学生端
											_this.updateUserInfo();
										}else{//教师端
											_this.successCallBack();
										}
								  }else{//请先绑定手机号
									_this.failCallBack();
									app.globalData.LOGION = false;
								}
						    })
						  }
						})
					}
				})
			},
			loginFun(success, fail) {
				//0学生 1教师
				let _this = this;
				let type = this.comIdentity;
				app.globalData.userIdentity = type;
				uni.login({
					success: ({ code }) => {
						request({
							url: `${app.globalData.BASE_URL}/${type==0?'api':'teacher'}/v1/user/auth?code=${code}`
						}).then(({ code, data, msg }) => {
							switch (Number(code)) {
								case 1:
									_this.showToast('登录成功');
									app.globalData.LOGION = true;
									uni.setStorageSync('app_token',type==0?data.token:data.teachertoken);
								uni.setStorageSync('user_identity', type);
								case 9997:
									uni.setStorageSync('wxapp_openid', data.wxapp_openid);
									break;
								case 991:
									_this.showToast(msg || '您是学生，请登录学生端');
									break;
								case 992:
									_this.toLoginTeacher()// 需要去登录教师端
									break;
								default:
									_this.showToast(msg || '请稍后再试');
									break;
							}
							setTimeout(()=>{
								success && success(Number(code),data);
							},20)
						}).catch(err=>{
							_this.showToast(err.msg || '请稍后再试');
						});
					}
				});
			},
			updateUserInfo(){
				API.updateUserInfo({
					avatar: this.avatar,
					nickname: this.nickname
				}).then(res => {
					if(res.code==1){
						this.successCallBack();
					}
				});
			}
		}
	}
</script>

<style scoped lang="scss">
.popup {
	width: 640rpx;
	height: 376rpx;
	background-color: #ffffff;
	border-radius: 24rpx;
	.top {
		padding: 48rpx;
		text-align: center;
		.title,
		.content {
			font-size: 34rpx;
			line-height: 48rpx;
			color: #666666;
			text-align: center;
		}
		.title {
			color: #000000;
			opacity: 0.9;
			margin: 0 auto 24rpx;
			padding: 0;
		}
	}
	.btn_bottom {
		width: 640rpx;
		height: 112rpx;
		display: flex;
		justify-content: space-between;
		.next_icon,
		.return_icon {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 34rpx;
			line-height: 48rpx;
			position: relative;
			border-top: 1rpx solid #f8f8f8;
		}
		.return_icon {
			color: #666666;
			opacity: 0.9;
			border-right: 1rpx solid #f8f8f8;
		}
		.next_icon {
			color: #333333;
		}
	}
}
</style>
